import config
import json
import requests as req
from utils import *


def register():
	return Coronavirus()


class Coronavirus:
	def __init__(self):
		self.type = 'passive'

	def search(self, node, name):
		return self.recursive(node, name, [], [])

	def recursive(self, node, name, dirs, results):
		dirs.append(node['name'])
		if node['name'] == name:
			log(node, dirs)
			results.append({
				'name': '-'.join(dirs),
				'totalConfirm': node['total']['confirm'],
				'nowConfirm': node['total']['nowConfirm'],
				'todayConfirm': node['today']['confirm'],
				'totalHeal': node['total']['heal'],
				'totalDead': node['total']['dead']
			})
		if not 'children' in node.keys():
			dirs.pop()
			return results
		for sub in node['children']:
			self.recursive(sub, name, dirs, results)
		dirs.pop()
		return results

	def run(self, gum, msg):
		if not msg['type'] in ['FriendMessage', 'GroupMessage'] \
				or len(msg['messageChain']) <= 1 \
				or msg['messageChain'][1]['type'] != 'Plain' \
				or msg['messageChain'][1]['text'].split()[0] != '*疫情':
			return

		text = msg['messageChain'][1]['text']
		splitted = text.split()

		with trying():
			data = json.loads(req.get('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5').json()['data'])
			chain = MsgChain()
			chain.addPlain('更新时间：' + data['lastUpdateTime'] + '\n')
			chain.addPlain('糖糖提醒您，更新可能存在延迟，数据仅供参考\n')
			keyword = '中国'
			if len(splitted) > 1:
				keyword = splitted[1]
			for item in self.search(data['areaTree'][0], keyword):
				chain.addPlain(item['name'] + ':\n')
				chain.addPlain('\t累计确诊：' + str(item['totalConfirm']) + '\n')
				chain.addPlain('\t现有确诊：' + str(item['nowConfirm']) + '\n')
				chain.addPlain('\t新增确诊：' + str(item['todayConfirm']) + '\n')
				chain.addPlain('\t累计治愈：' + str(item['totalHeal']) + '\n')
				chain.addPlain('\t累计死亡：' + str(item['totalDead']) + '\n')

		if msg['type'] == 'FriendMessage':
			post('sendFriendMessage', target=msg['sender']['id'], messageChain=chain.content)
		elif msg['type'] == 'GroupMessage':
			post('sendGroupMessage', target=msg['sender']['group']['id'], messageChain=chain.content)
